﻿using System;
using System.Net;
using System.Security;
using System.Xml.Linq;
using System.Linq;
using NLog;

namespace Definition.WebImport
{
    /// <summary>
    /// Request für Film-Informationen anhand eines Suchterms
    /// </summary>
    public abstract class TmdbRequest
    {
        protected Logger logger = LogManager.GetCurrentClassLogger();

        public abstract string GetUrl();

        public XElement GetMoviesElement(string request)
        {
            var xml = GetXml(request);

            var elements = xml.Root.Elements();

            if (elements.Count() == 0)
                throw new ArgumentException("Die Xml-Antwort hat keine Elemente");
            else
            {              
                //In xml-Response 3tes Element
                return elements.ElementAt(2);
            }
        }

        private XDocument GetXml(string request)
        {        
            var webRequest = WebRequest.Create(GetRequestUrl(request));
            webRequest.Timeout = 20000;

            var response = webRequest.GetResponse();

            if (response == null)
                throw new ArgumentNullException("Web-Response");

            var stream = response.GetResponseStream();

            if (stream == null)
                throw new ArgumentNullException("stream");

            var xml = XDocument.Load(stream);

            if (xml == null)
                throw new ArgumentNullException("xml");

            stream.Close();
            response.Close();

            return xml;       
        }

        private string GetRequestUrl(string request)
        {
            var requestUrl = String.Format("{0}{1}", GetUrl(), request);
            requestUrl = requestUrl.Replace(" ", "+");
            return requestUrl;
        } 
    }
}
